package com.xzuf.extend;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.apache.commons.lang.StringUtils;

import com.xzuf.core.vo.xml.DataSourceVO;
import com.xzuf.nc.BDImportTools;
import com.xzuf.nc.CntrastFieldDialog;
import com.xzuf.nc.NCValues;
import com.xzuf.nc.TempletSchemeVO;
import com.xzuf.plugin.IModulePlugin;
import com.xzuf.pub.DbUtils;
import com.xzuf.pub.FileUtils;
import com.xzuf.pub.GlobalValue;
import com.xzuf.pub.GuiUtils;
import com.xzuf.pub.UFDouble;

/**
 * NC档案导入工具
 * @author xzgf
 * @since 2008-9-10
 * @version 1.0
 */
public class NCBaseDocumentExportPanel implements IModulePlugin ,ItemListener,ActionListener{
	
	private JComboBox cb_bdocType = null; //
	
	private JButton btnGenXml = null; //
	
	private JButton btnImport = null; //
	
	private JCheckBox cb_isU8 = null;
	
	private JTextField tf_Sql = null;
	
	private JTextField tf_sender = null;
	
	private JTextField tf_receiver = null;
	
	private JTextField tf_account = null;
	
	private JTextField tf_dir = null;
	
	private JTextField tf_taxitems = null;
	
	private JTextField tf_corp  = null;
	
	private JTextField tf_totalField = null;
	
	private JButton btnChangeDir = null;
	
	private JButton btnDefault = null;
	
	private JButton btnDefaultSql = null;
	
	private JButton btnResolve = null;
	
	private List<List<TempletSchemeVO>> scheme;
	
	@Override
	public int getCurrentOpState() {
		return 0;
	}

	@Override
	public void setCurrentOpState(int state) {
	}

	@Override
	public JPanel start() {
		
		cb_bdocType = new JComboBox();
		cb_bdocType.addItemListener(this);
		DefaultComboBoxModel model = new DefaultComboBoxModel();
		model.addElement(NCValues.BasicDoc);
		model.addElement(NCValues.INVTYPE);
		model.addElement(NCValues.ARAP);
		model.addElement(NCValues.IC);
		model.addElement(NCValues.PO_ORDER);
		model.addElement(NCValues.VOUCHER);
		model.addElement(NCValues.INBill);
		model.addElement(NCValues.OUTBill);
		cb_bdocType.setModel(model);
		
		JLabel lb_1 = new JLabel("NC档案类型");
		lb_1.setBounds(10, 10, 100, 22);
		cb_bdocType.setBounds(120, 10, 120, 22);
		
		btnGenXml = new JButton("生成");
		btnGenXml.addActionListener(this);
		btnGenXml.setBounds(250, 10, 80, 22);
		
		btnImport = new JButton("导入");
		btnImport.setEnabled(false);
		btnImport.addActionListener(this);
		btnImport.setBounds(340, 10, 80, 22);
		
		cb_isU8 = new JCheckBox("U8");
		cb_isU8.setSelected(false);
		cb_isU8.setToolTipText("此选项只针对U8凭证有效...");
		cb_isU8.setBounds(430, 10, 80, 22);
		
		JLabel lb_2 = new JLabel("SQL");
		lb_2.setBounds(10, 42, 80, 22);
		tf_Sql = new JTextField();
		tf_Sql.setText("select cBillCode,cSOCode,cWHCode,cInvCode,cDepCode,iNum,iPrice,iMoney,dIWDate,cInCode,dInDate from IcTable");
		tf_Sql.setBounds(100, 42, 600, 22);
		
		btnResolve = new JButton("方案设置");
		btnResolve.addActionListener(this);
		btnResolve.setBounds(710, 42, 100, 22);
		
		btnDefaultSql = new JButton("缺省SQL");
		btnDefaultSql.addActionListener(this);
		btnDefaultSql.setBounds(820, 42, 100, 22);
		
		JLabel lb_3 = new JLabel("Receiver");
		lb_3.setBounds(10, 74, 80, 22);
		JLabel lb_4 = new JLabel("Sender");
		lb_4.setBounds(170, 74, 80, 22);
		tf_receiver = new JTextField();
		tf_receiver.setText("0001");
		tf_receiver.setBounds(100, 74, 60, 22);
		tf_sender = new JTextField();
		tf_sender.setText("0101");
		tf_sender.setBounds(260, 74, 60, 22);
		JLabel lb_41 = new JLabel("����");
		lb_41.setBounds(330, 74, 60, 22);
		tf_account = new JTextField();
		tf_account.setText("001");
		tf_account.setBounds(400, 74, 60, 22);
		
		JLabel lb_42 = new JLabel("主键");
		lb_42.setBounds(470, 74, 60, 22);
		tf_taxitems = new JTextField();
		tf_taxitems.setText("cBillCode");
		tf_taxitems.setBounds(540, 74, 60, 22);
		
		JLabel lb_43 = new JLabel("公司");
		lb_43.setBounds(610, 74, 60, 22);
		tf_corp = new JTextField();
		tf_corp.setText("0001");
		tf_corp.setBounds(680, 74, 60, 22);
		
		JLabel lb_44 = new JLabel("汇总字段");
		lb_44.setBounds(750, 74, 60, 22);
		tf_totalField = new JTextField();
		tf_totalField.setText("");
		tf_totalField.setBounds(820, 74, 100, 22);
		tf_totalField.setToolTipText("用户多行数据的汇总..");
		
		JLabel lb_5 = new JLabel("生成文件位置");
		lb_5.setBounds(10, 106, 80, 22);
		tf_dir = new JTextField();
		tf_dir.setEnabled(false);
		tf_dir.setText(GlobalValue.USR_DIR + "\\ncxml");
		tf_dir.setBounds(100, 106, 400, 22);
		btnChangeDir = new JButton("改变位置");
		btnChangeDir.setBounds(510, 106, 100, 22);
		btnChangeDir.addActionListener(this);
		
		btnDefault = new JButton("缺省位置");
		btnDefault.setBounds(620, 106, 100, 22);
		btnDefault.addActionListener(this);
		
		
		JPanel panel = new JPanel();
		panel.setLayout(null);
		
		panel.add(lb_1);
		panel.add(cb_bdocType);
		panel.add(btnGenXml);
		panel.add(btnImport);
		panel.add(cb_isU8);
		panel.add(lb_2);
		panel.add(tf_Sql);
		panel.add(btnResolve);
		panel.add(btnDefaultSql);
		
		panel.add(lb_3);
		panel.add(tf_receiver);
		panel.add(lb_4);
		panel.add(tf_sender);
		panel.add(lb_41);
		panel.add(tf_account);
		panel.add(lb_42);
		panel.add(tf_taxitems);
		panel.add(lb_43);
		panel.add(tf_corp);
		panel.add(lb_44);
		panel.add(tf_totalField);
		
		panel.add(lb_5);
		panel.add(tf_dir);
		panel.add(btnChangeDir);
		panel.add(btnDefault);
		
		
		return panel;

	}
	
	private void onBoImport() {
		
	}
	
	private void onBoGenXml() {
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		try {
			GlobalValue.sysProp = FileUtils.getSystemPropertyFromXML(GlobalValue.CONFIG_FILE_BAT);
			if(GlobalValue.DefaultDataSource == null) {
				GuiUtils.showMessage("缺省数据源为空,请设置然后重启..", GlobalValue.mainFrame);
				return;
			}
			DataSourceVO dataSourceVO = GlobalValue.DefaultDataSource;
			conn = DbUtils.createDbConnection(dataSourceVO);
			pstmt = conn.prepareStatement(tf_Sql.getText().trim());
			ResultSet rs = pstmt.executeQuery();
//			NCInvDoc invDoc = null;
			int count = 0;
			long startTime = System.currentTimeMillis();
//			if(String.valueOf(cb_bdocType.getSelectedItem()).equals(NCValues.INVDOC)) {
//				
//				while(rs.next()) {
//					invDoc = new NCInvDoc();
//					invDoc.setM_invcode(rs.getString("cinvcode"));
//					invDoc.setM_invname(rs.getString("cinvname"));
//					if(rs.getString("cinvstd") != null) {
//						invDoc.setM_invspec(rs.getString("cinvstd"));	
//					} else {
//						invDoc.setM_invspec("");	
//					}
//					if(rs.getString("cinvccode") != null) {
//						invDoc.setM_pk_invcl(rs.getString("cinvccode"));
//					} else {
//						invDoc.setM_pk_invcl("");
//					}
//					if(rs.getBigDecimal("iinvsprice") == null) {
//						invDoc.setM_unitweight(new UFDouble(0));
//					} else {
//						invDoc.setM_unitweight(new UFDouble(rs.getBigDecimal("iinvsprice")));
//					}
//					if(rs.getString("ccomunitcode") != null) {
//						invDoc.setM_pk_measdoc(rs.getString("ccomunitcode"));
//					} else {
//						invDoc.setM_pk_measdoc("");	
//					}
//					if(rs.getString("cinvaddcode") != null) {
//						invDoc.setM_invtype(rs.getString("cinvaddcode"));
//					} else {
//						invDoc.setM_invtype("");	
//					}
//					BDImportTools.genInvDocXml(invDoc, tf_sender.getText().trim(), tf_receiver.getText().trim(), invDoc.getM_invcode(),tf_dir.getText(),tf_taxitems.getText(),tf_corp.getText());
//					count++;
//				}
//			}
			if(scheme == null ) {
				JOptionPane.showMessageDialog(GlobalValue.mainFrame,"方案为空,请选择..");
				return;
			}
			
			List<String> colList = BDImportTools.parseSqlField(tf_Sql.getText().trim());
			
			String[] totalCol = null;
			if(StringUtils.isNotEmpty(tf_totalField.getText())) {
				totalCol = tf_totalField.getText().trim().split(",");
			}
			if(scheme.size() == 1) {
				count = BDImportTools.genDocXmlFile(rs,String.valueOf(cb_bdocType.getSelectedItem()), scheme.get(0), null,tf_sender.getText().trim(), tf_receiver.getText().trim(), tf_taxitems.getText().trim(), tf_dir.getText(), tf_corp.getText());
			}
			if(scheme.size() == 2 && cb_isU8.isSelected()) {
				count = BDImportTools.genDocXmlFileForU8(rs,String.valueOf(cb_bdocType.getSelectedItem()),colList,totalCol, scheme.get(0), scheme.get(1),tf_sender.getText().trim(), tf_receiver.getText().trim(), tf_taxitems.getText().trim(),"inid", tf_dir.getText(), tf_corp.getText());
			}
			if(scheme.size() == 2) {
				count = BDImportTools.genDocXmlFile(rs,String.valueOf(cb_bdocType.getSelectedItem()),colList,totalCol, scheme.get(0), scheme.get(1),tf_sender.getText().trim(), tf_receiver.getText().trim(), tf_taxitems.getText().trim(), tf_dir.getText(), tf_corp.getText());
			}
			
			long endTime = System.currentTimeMillis();
			UFDouble second = (new UFDouble(endTime).sub(new UFDouble(startTime))).div(new UFDouble(1000)).setScale(2, UFDouble.ROUND_HALF_UP);
			JOptionPane.showMessageDialog(GlobalValue.mainFrame, "生成成功,共生成....��[" + count + "]个文件,耗时:[" + second + "]秒");
		} catch (FileNotFoundException e) {
			JOptionPane.showMessageDialog(GlobalValue.mainFrame, e.getMessage());
			e.printStackTrace();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(GlobalValue.mainFrame, e.getMessage());
			e.printStackTrace();
		} finally {
			try {
				conn.close();
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void onBoDir() {
		JFileChooser fileChooser = new JFileChooser(System.getProperty("c:/"));
		fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		int flag = fileChooser.showSaveDialog(GlobalValue.mainFrame);
		if(flag != JFileChooser.APPROVE_OPTION) {
			return;
		}
		File file = fileChooser.getSelectedFile();
		tf_dir.setText(file.getAbsolutePath());
	}
	
	private void onBoDefault() {
		tf_dir.setText(GlobalValue.USR_DIR + "\\ncxml");
	}
	
	private void onBoDefaultSql() {
		tf_Sql.setText("select cinvcode,cinvname,cinvstd,cinvccode,itaxrate,iinvsprice,ccomunitcode from tableName");
	}
	 
	private void onBoResolve() {
		String docType = String.valueOf(cb_bdocType.getSelectedItem());
		String str = String.valueOf(tf_Sql.getText());
		if(str == null || StringUtils.isEmpty(str)) {
			JOptionPane.showMessageDialog(GlobalValue.mainFrame, "SQL语句为空..");
			return;
		}
		CntrastFieldDialog dialog = new CntrastFieldDialog(GlobalValue.mainFrame,docType,str);
		dialog.setVisible(true);
		scheme = dialog.getCurrentScheme();
		System.out.println(scheme);
	}

	@Override
	public void itemStateChanged(ItemEvent e) {
		if(e.getSource() == cb_bdocType) {
			String str = String.valueOf(cb_bdocType.getSelectedItem());
			if(str.equals(NCValues.U8)) {
				
			}
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(btnGenXml.equals(e.getSource())) {
			onBoGenXml();
		}
		if(btnImport.equals(e.getSource())) {
			onBoImport();
		}
		if(btnChangeDir.equals(e.getSource())) {
			onBoDir();
		}
		if(btnDefault.equals(e.getSource())) {
			onBoDefault();
		}
		if(btnDefaultSql.equals(e.getSource())) {
			onBoDefaultSql();
		}
		if(btnResolve.equals(e.getSource())) {
			onBoResolve();
		}
	}

	
	
}
